package net.ezsteam.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.ezsteam.EzSteam_LoginActivity;
import net.ezsteam.EzSteam_ServiceType_Activity;
import net.ezsteam.EzSteam_StoreVisit_Activity;
import net.ezsteam.R;
import net.ezsteam.EzSteam_Register_Activity.MyAdapter;
import net.ezsteam.cons.EzSteam_Urls;
import net.ezsteam.view.EzSteam_HorizontialListView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class EzSteam_Appoinment_Service extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	private MyAdapter myAdapter;
	
	private boolean exeption = false;
	
	private ListView listview;
	
	//List<String> list;
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();
	
	String[] arrTime;
	String[] arrType;
	String[] arrAddrs;
	String[] arrPhone;
	String[] arrStatus;
	String[] arrID;
	String[] arrCusID;
	String[] arrStoreLoc;

	
	public EzSteam_Appoinment_Service(Activity activity,ListView listview) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.listview = listview;
		
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Appoinments", "Loading Appoinments, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {

		try {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(urls[0]));
		    
			HttpEntity httpEntity = response.getEntity();

			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				exeption = true;
				e.printStackTrace();
			} catch (Exception e) {
				exeption = true;
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		
		Log.d("Post Apponiment", result);
		progdialod.dismiss();

		
		Log.d("Post Exec", result); //"result" is the token *if not null
		
		
			if(!exeption){
				
				try {

					JSONObject jsonobj = new JSONObject(result);
					JSONArray service_type = jsonobj.getJSONArray("appointment_deatils");

					arrTime = new String[service_type.length()];
					arrType = new String[service_type.length()];
					arrAddrs = new String[service_type.length()];
					arrPhone = new String[service_type.length()];
					arrStatus = new String[service_type.length()];
					arrID = new String[service_type.length()];
					arrCusID = new String[service_type.length()];
					arrStoreLoc = new String[service_type.length()];
					
					for(int typei=0;typei<service_type.length();typei++){
						if(service_type.get(typei) instanceof JSONObject){
							JSONObject jsonDetails = service_type.getJSONObject(typei);
							arrTime[typei] = jsonDetails.getString("reserve_time");
							arrType[typei] = jsonDetails.getString("type");
							arrAddrs[typei] = jsonDetails.getString("location_address");
							arrStoreLoc[typei] = jsonDetails.getString("store_location");
							arrPhone[typei] = jsonDetails.getString("contact_phone");
							arrStatus[typei] = jsonDetails.getString("status");
							arrID[typei] = jsonDetails.getString("id");
							arrCusID[typei] = jsonDetails.getString("customer_id");
							//list.add(""+jsonDetails.getString("reserve_time")+" "+jsonDetails.getString("type")+" "+jsonDetails.getString("location_address")+" "+jsonDetails.getString("contact_phone")+" "+jsonDetails.getString("status"));
						}
					}

					if(arrTime.length != 0){

					    myAdapter = new MyAdapter();

				        listview.setAdapter(myAdapter);
				        //listview.setAdapter(mAdapter2);
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				
				
				
			
			}else{
				Toast toast = Toast.makeText(activity, "Failed !!", Toast.LENGTH_SHORT);
				toast.show();
			}

	}
	
	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		
		public MyAdapter() {
			 mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		 @Override
	        public int getCount() {
	            return arrTime.length;
	        }
	 
	        @Override
	        public Object getItem(int position) {
	            return arrTime[position];
	        }
	 
	        @Override
	        public long getItemId(int position) {
	            return position;
	        }
	 
	        @Override
	        public View getView(final int position, View convertView, ViewGroup parent) {
	        	//convertView = mInflater.inflate(R.layout.ezsteam_appoinment_row, null);
	            View retval = LayoutInflater.from(activity).inflate(R.layout.ezsteam_appoinment_row, null);
	            TextView txt_data_time = (TextView) retval.findViewById(R.id.txt_data_time);
	            TextView txt_data_type = (TextView) retval.findViewById(R.id.txt_data_type);
	            TextView txt_data_location = (TextView) retval.findViewById(R.id.txt_data_location);
	            TextView txt_data_phone = (TextView) retval.findViewById(R.id.txt_data_phone);
	            TextView txt_data_status = (TextView) retval.findViewById(R.id.txt_data_status);
	            
	            txt_data_time.setText(arrTime[position]);
	            txt_data_type.setText(arrType[position]);
	            txt_data_location.setText(arrAddrs[position]);
	            txt_data_phone.setText(arrPhone[position]);
	            txt_data_status.setText(arrStatus[position]);
	            
	            Button btnRecall = (Button) retval.findViewById(R.id.btn_recall);
	            Button btnCancel = (Button) retval.findViewById(R.id.btn_cancel);
	            Button btnModify = (Button) retval.findViewById(R.id.btn_modify);
	            
	            btnRecall.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
							Intent intent = new Intent(activity,EzSteam_StoreVisit_Activity.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							Bundle bundle = new Bundle();
							bundle.putString("cusid", arrCusID[position]);
							bundle.putString("datetime", "");//Do Not Send Date For Recall
							bundle.putString("contact_number", arrPhone[position]);
							bundle.putString("type", arrType[position]);
							bundle.putString("appID", arrID[position]);
							bundle.putBoolean("isRecall", true);
							bundle.putString("address", arrAddrs[position]);
							bundle.putString("locID", arrStoreLoc[position]);
							intent.putExtras(bundle);
							activity.startActivity(intent);
						
					}
				});
	            
	            btnCancel.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
						    @Override
						    public void onClick(DialogInterface dialog, int which) {
						        switch (which){
						        case DialogInterface.BUTTON_POSITIVE:
						            
						        	EzSteam_Appoinment_Cancel_Service acs = new EzSteam_Appoinment_Cancel_Service(activity,arrCusID[position],arrID[position]);
						        	acs.execute(EzSteam_Urls.GET_Cancel_Appoinment);
						        	
						            break;

						        case DialogInterface.BUTTON_NEGATIVE:
						            break;
						        }
						    }
						};

						AlertDialog.Builder builder = new AlertDialog.Builder(activity);
						builder.setMessage("Confirm Cancelation?").setPositiveButton("Yes", dialogClickListener)
						    .setNegativeButton("No", dialogClickListener).show();
					}
				});

	            btnModify.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(arrType[position].equals("0")){
							
							Intent intent = new Intent(activity,EzSteam_StoreVisit_Activity.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							Bundle bundle = new Bundle();
							bundle.putString("cusid", arrCusID[position]);
							bundle.putString("datetime", arrTime[position]);
							bundle.putString("contact_number", arrPhone[position]);
							bundle.putBoolean("isUpdate", true);
							bundle.putString("type", arrType[position]);
							bundle.putString("appID", arrID[position]);
							bundle.putString("address", arrAddrs[position]);
							bundle.putString("locID", arrStoreLoc[position]);
							
							intent.putExtras(bundle);
							activity.startActivity(intent);
							
						}else if(arrType[position].equals("1")){
							
						}
					}
				});
	            
	            return retval;
	        }
	}


}
